<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;

class Palindrome extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'palindrome {str} {char}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Command description';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }



    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        $str = $this->argument("str");
        $char = $this->argument("char");
        $positions = $this->allPositions($str, $char);
        $e = $this->getlongestPalindrome($str, $positions);
        return 0;
    }

    private function getlongestPalindrome($str, $positions){
        $length = 0;
        $longest = '';
        for ($start=0;$start<count($positions);$start++){
            for ($end=count($positions)-1;$end>=$start;$end--){
                $tmp = substr($str, $positions[$start], $positions[$end]-$positions[$start]+1);
                if($this->isPalindrome($tmp)){
                    if(strlen($tmp)>$length){
                        $length = strlen($tmp);
                        $longest = $tmp;
                    }
                }
            }
        }
        return $longest;
    }


    private function allPositions($str, $c){
        $index = 0;
        $positions =[];
        while(true){
            $index = strpos($str, $c, $index);
            if($index===false){
                break;
            }
            array_push($positions, $index);
            $index = $index+1;
        }

        return $positions;
    }

    /**
     * 检测字符串是否是回文
     * @param $str
     * @return bool
     */
    private function isPalindrome($str){
        if(empty($str)){
            return false;
        }
        return $str === strrev($str);
    }
}
